// 使用PBKDF2生成密钥
export async function deriveKey(password, salt) {
    const encoder = new TextEncoder();
    const passwordBuffer = encoder.encode(password);
    const saltBuffer = encoder.encode(salt);

    // 使用PBKDF2生成密钥材料
    const keyMaterial = await window.crypto.subtle.importKey(
        'raw',
        passwordBuffer,
        'PBKDF2',
        false,
        ['deriveBits']
    );

    // 生成256位（32字节）的密钥
    const keyBuffer = await window.crypto.subtle.deriveBits(
        {
            name: 'PBKDF2',
            salt: saltBuffer,
            iterations: 50000,
            hash: 'SHA-256'
        },
        keyMaterial,
        256 // 生成256位密钥
    );

    // 转换为十六进制字符串
    const derivedKey = Array.from(new Uint8Array(keyBuffer))
        .map(b => b.toString(16).padStart(2, '0'))
        .join('');
    
    console.log('Frontend derived key:', derivedKey);
    return derivedKey;
}

// 加密数据
export async function encrypt(data, keyHex) {
    console.log('Frontend encrypt params:', { data, keyHex });
    const encoder = new TextEncoder();
    const iv = window.crypto.getRandomValues(new Uint8Array(12));
    
    // 从十六进制字符串导入密钥
    const keyBuffer = new Uint8Array(keyHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
    const cryptoKey = await window.crypto.subtle.importKey(
        'raw',
        keyBuffer,
        'AES-GCM',
        false,
        ['encrypt']
    );

    // 加密数据
    const encryptedData = await window.crypto.subtle.encrypt(
        {
            name: 'AES-GCM',
            iv: iv
        },
        cryptoKey,
        encoder.encode(data)
    );

    // 转换为十六进制字符串
    const result = {
        encrypted: Array.from(new Uint8Array(encryptedData))
            .map(b => b.toString(16).padStart(2, '0'))
            .join(''),
        iv: Array.from(iv)
            .map(b => b.toString(16).padStart(2, '0'))
            .join('')
    };
    
    console.log('Frontend encrypt result:', result);
    return result;
}

// 解密数据
export async function decrypt(encryptedHex, ivHex, keyHex) {
    console.log('Frontend decrypt params:', { encryptedHex, ivHex, keyHex });
    
    // 从十六进制字符串导入密钥
    const keyBuffer = new Uint8Array(keyHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
    const cryptoKey = await window.crypto.subtle.importKey(
        'raw',
        keyBuffer,
        'AES-GCM',
        false,
        ['decrypt']
    );

    // 转换IV和加密数据
    const iv = new Uint8Array(ivHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
    const encrypted = new Uint8Array(encryptedHex.match(/.{2}/g).map(byte => parseInt(byte, 16)));

    // 解密
    const decrypted = await window.crypto.subtle.decrypt(
        { name: 'AES-GCM', iv },
        cryptoKey,
        encrypted
    );

    // 转换为字符串
    const result = new TextDecoder().decode(decrypted);
    console.log('Frontend decrypt result:', result);
    return result;
}
